import { constantRoutes } from '@/router'
import store from '../index'
import { getMenu } from '@/api/system/permissions'
import Layout from '@/layout'

/**
 * Use meta.permission to determine if the current user has permission
 * @param permissions
 * @param route
 */
function hasPermission(permissions, route) {
  if (route.meta && route.meta.permissions) {
    return permissions.some(permission => route.meta.permissions.includes(permission))
  } else {
    return true
  }
}

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes(有权限控制的路由)
 * @param permissions
 */
export function filterAsyncRoutes(routes, permissions) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(permissions, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, permissions)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [], addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

/**
 * 格式化菜单数据
 * @param routesData
 * @returns {*}
 */
export function generateDynamicRoutes(routesData) {
  let result
  // eslint-disable-next-line prefer-const
  result = routesData.map(route => {
    if (!route?.children?.length) {
      return {
        path: `/${route.sign}`,
        component: Layout,
        children: [
          {
            path: 'index',
            component: (resolve) => require([`@/views/${route.sign}/index`], resolve),
            name: route.name,
            meta: { title: route.name, icon: route.icon, noCache: true }
          }
        ]
      }
    } else {
      return {
        path: `/${route.sign}`,
        component: Layout,
        redirect: 'noRedirect',
        alwaysShow: true,
        name: route.sign,
        meta: {
          permissions: ['admin', route.sign],
          title: route.name,
          icon: route.icon
        },
        children: route.children.map(ch => {
          return {
            component: (resolve) => require([`@/views/${ch.sign.replace('-', '/')}`], resolve),
            path: ch.sign.replace(`${route.sign}-`, ''),
            name: ch.sign,
            meta: {
              permissions: ['admin', ch.sign],
              title: ch.name,
              icon: ch.icon,
              noCache: true
            }
          }
        })
      }
    }
  })
  // 404页必须放在最后！
  result.push({ path: '*', redirect: '/404', hidden: true })
  return result
}

const actions = {
  async generateRoutes({ commit }) {
    return new Promise(resolve => {
      store.dispatch('user/getInfo').then(async res => {
        const rr = await getMenu()
        const rrr = generateDynamicRoutes(rr.data)
        const accessedRoutes = filterAsyncRoutes(rrr, res.permissions)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true, state, mutations, actions
}
